import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'

// 超时时间
const TIMEOUT = 5 * 60 * 1000
const WEEK = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

//最后一次成功的http操作时间
let lasttime = -1

/**
 * 刷新操作时间
 */
const flushLasttime = () => {
  lasttime = new Date().getTime()
}

/**
 * 判断session是否超时
 */
const isTimeout = () => {
  return (new Date().getTime() - lasttime - TIMEOUT) > 0
}

/**
 * 工时管理 store
 */
export default {
  state: {
    user: {
      // userName: 'LCBJ09987',
      // password: '17Xanwtdwi',
      userName: '',
      password: '',
      firstclass: '',
      maintainsubs: '',
      projectid: '',
      projectleader: '',
      memo: '',
      projectName: '',
      maintainsubsName: ''
    },
    autoMemo: [],
    times: [],
    projects: [],
    //保存最近一周的工时数据
    // times: [{
    //   "id": 773398,
    //   "classtype": null,
    //   "budget_number": null,
    //   "second_dep": null,
    //   "product_line": null,
    //   "group_id": null,
    //   "uesr_type": null,
    //   "user_status": null,
    //   "user_id": "LCBJ09987",
    //   "times": "2018-12-29",
    //   "project_name": "Aloe V1",
    //   "project_id": 723,
    //   "work_time": 9.12,
    //   "status": 0,
    //   "total_time": 0.0,
    //   "process_byname": "无",
    //   "process_department": null,
    //   "process_time": "2018-12-29 14:41:17",
    //   "memo": "多设备首页优化多设备首页优",
    //   "project_status": null,
    //   "departMent": null,
    //   "station": null,
    //   "passto1": null,
    //   "passto2": null,
    //   "name": null,
    //   "process_bynamenew": null,
    //   "myname": null,
    //   "projectlead": "赵鹏",
    //   "advice": "",
    //   "classType": null,
    //   "maintainSubs": null,
    //   "workd_time": 9.0,
    //   "statusInfo": "未审批",
    //   "week": "一"
    // }],
    // projects: [{
    //   "id": -1,
    //   "budget_number": null,
    //   "project_name": "...",
    //   "product_name": null,
    //   "project_leader": null,
    //   "leads": null
    // }],
    maintainsubses: [{
      name: '市场问题处理',
      value: '1'
    },{
      name: '生产问题处理',
      value: '2'
    },{
      name: '市场需求',
      value: '3'
    },{
      name: '例行升级',
      value: '4'
    }],
    leaders: []
  },
  getters: {
    timesUser (state) {
      return state.user
    },
    times (state) {
      return state.times
    },
    projects (state) {
      return state.projects
    },
    leaders (state) {
      return state.leaders
    },
    maintainsubses (state) {
      return state.maintainsubses
    },
    autoMemo (state) {
      return state.autoMemo
    }
  },
  mutations: {
    setUser(state, user) {
      Vue.set(state, 'user', user)
      localStorage.__timesuser = JSON.stringify(state.user)
      if (! user.userName){
        //重置用户操作，此时需重置最后操作时间，消除前一个用户session的影响
        lasttime = -1
      }
    },
    setTimes(state, times) {
      Vue.set(state, 'times', times)
    },
    setProjects (state, projects) {
      Vue.set(state, 'projects', projects)
    },
    setLeaders (state, leaders) {
      Vue.set(state, 'leaders', leaders)
    },
    addAutoMemo (state, value) {
      if (! state.autoMemo.filter(x => x.value === value).length) {
        state.autoMemo.push({ value })
        if (state.autoMemo.length > 10) {
          state.autoMemo.shift()
        }
        localStorage.__memo = JSON.stringify(state.autoMemo)
      }
    },
    loadUser (state) {
      if (localStorage.__timesuser && localStorage.__timesuser !== 'undefined') {
        Vue.set(state, 'user', JSON.parse(localStorage.__timesuser))
      }
      if (localStorage.__memo && localStorage.__memo !== 'undefined') {
        Vue.set(state, 'autoMemo', JSON.parse(localStorage.__memo))
      }
    }
  },
  actions: {
    /**
     * 检查用户名密码是否可登录成功
     */
    runLogin ({ rootGetters }, user) {
      return new Promise((resolve, reject) => {
        if (isTimeout()) {
          let params = qs.stringify(user)
          axios({
            method: 'post',
            url: rootGetters.urlTimesLogin,
            headers: {
             'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            data: params,
            params
          })
          .then(result => {
            console.log('login times : ', result)
            if (result && result.data) {
              let regx = /var _errorMsg = "(.*)"/
              let match = regx.exec(result.data)
              if (match && match.length == 2) {
                  console.log('登录失败:' + match[1])
                  reject(match[1])
                  return
              } else if (result.data.indexOf('工时录入') !== -1) {
                //登录成功
                flushLasttime()
                console.log('登录成功')
                resolve('0')
                return
              }
            }
            reject('登录失败,请检查网络是否正常!')
          })
          .catch(e => {
            console.log('send request error:', e)
            reject('网络异常:' + e.message)
          })
        } else {
            console.log('登录未超时')
            resolve('0')
        }
      })
    },
    /**
     * 登录,成功时返回 '0', 失败时返回异常信息
     * @param force 为true时表示 
     */
    login ({ dispatch, state, rootGetters }, force) {
      if (rootGetters.isDev && !force) {
        //由于node.js不能代理 redirect 响应，开发环境登录成功后会返回失败，此处强制成功
        return new Promise((resolve) => {
          resolve('0')
        })
      }

      return dispatch ('runLogin', state.user)
    },

    /**
     * 获取工时历史,生成最近一周的工时数据
     */
    getTimes ({ commit, state, rootGetters, dispatch }) {
      return dispatch('login').then(() => {
        let form = {
          draw: 1,
          start: 0,
          length: 10,
          userid: state.user.userName,
          '_': new Date().getTime()
        }
        let params = qs.stringify(form)

        return axios({
          method: 'get',
          url: rootGetters.urlTimesDetailList + '?' + params
        }).then(result => {
          return new Promise((resolve, reject) => {
            try{                 
              let data = (typeof(result.data) === 'string' ? JSON.parse(result.data) : result.data).data
              let day = new Date()
              day.setDate(day.getDate() - day.getDay())    //前一周的周日
              let times = WEEK.map(x => {
                day.setDate(day.getDate() + 1)
                let times = day.format('yyyy-MM-dd')
                //只考虑一天一条的情况
                let workTimes = data.filter(x => x.times === times)
                return Object.assign({ week: x }, workTimes.length ? workTimes[0] : { times })
              })
              commit('setTimes', times)
              //刷新最后操作时间
              flushLasttime()

              resolve()
            } catch (e) {
              reject(e.message)
            }
          })
        })
      })
    },
    /**
     * 获取项目
     * @param classtype 工时类型
     */
    getProjects ({ commit, rootGetters, dispatch }, classtype) {
      return dispatch('login').then(() => {
        let params = qs.stringify({ classtype })

        return axios({
          method: 'post',
          url: rootGetters.urlPojectType,
          data: params,
          params
        }).then(result => {
          let projectList = (typeof(result.data) === 'string' ? JSON.parse(result.data) : result.data).projectList
          commit('setProjects', projectList)
          //刷新最后操作时间
          flushLasttime()
        })
      })
    },
    /**
     * 获取负责人
     * @param id 项目id
     */
    getLeaders ({ commit, rootGetters, dispatch }, id) {
      return dispatch('login').then(() => {
        let params = qs.stringify({ id })

        return axios({
          method: 'post',
          url: rootGetters.urlProjectLeader,
          data: params,
          params
        }).then(result => {
          let leadList = (typeof(result.data) === 'string' ? JSON.parse(result.data) : result.data).leadList
          commit('setLeaders', leadList)
          //刷新最后操作时间
          flushLasttime()
        })
      })
    },
    /**
     * 新增工时
     */
    addWorkTime ({rootGetters, dispatch}, time) {
      return dispatch('login').then(() => {
        let params = qs.stringify(time)

        return axios({
          method: 'post',
          url: rootGetters.urlTimesAdd,
          data: params,
          params
        }).then(result => {
          let message = (typeof(result.data) === 'string' ? JSON.parse(result.data) : result.data).message
          //刷新最后操作时间
          flushLasttime()

          return new Promise((resolve, reject) => {
            message ? reject(message) : resolve()
          })
        })
      })
    },
    /**
     * 修改工时
     */
    updateWorkTime ({rootGetters, dispatch}, time) {
      return dispatch('login').then(() => {
        let params = qs.stringify(time)

        return axios({
          method: 'post',
          url: rootGetters.urlTimesChange,
          data: params,
          params
        }).then(result => {
          let message = (typeof(result.data) === 'string' ? JSON.parse(result.data) : result.data).message
          //刷新最后操作时间
          flushLasttime()

          return new Promise((resolve, reject) => {
            message ? reject(message) : resolve()
          })
        })
      })
    },
    /**
     * 提交工时
     */
    submitWorkTime ({rootGetters, dispatch}, id) {
      return dispatch('login').then(() => {
        //参数要这么设置我也很无语。。
        let params = qs.stringify({ 'ids[]': id })

        return axios({
          method: 'post',
          url: rootGetters.urlTimeSubmit,
          data: params,
          params
        }).then(result => {
          let message = (typeof(result.data) === 'string' ? JSON.parse(result.data) : result.data).message
          //刷新最后操作时间
          flushLasttime()

          return new Promise((resolve, reject) => {
            message ? reject(message) : resolve()
          })
        })
      })
    },
  }
}